home *** CD-ROM | disk | FTP | other *** search
/ Night Owl 6 / Night Owl's Shareware - PDSI-006 - Night Owl Corp (1990).iso / 016a / gofer221.zip / APPX_B < prev    next >
Text File  |  1991-11-20  |  28KB  |  925 lines

  1.  
  2.  
  3. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  4.  
  5.  
  6. APPENDIX B: CONTENTS OF STANDARD PRELUDE
  7.  
  8. --         __________   __________   __________   __________   ________
  9. --        /  _______/  /  ____   /  /  _______/  /  _______/  /  ____  \
  10. --       /  / _____   /  /   /  /  /  /______   /  /______   /  /___/  /
  11. --      /  / /_   /  /  /   /  /  /  _______/  /  _______/  /  __   __/
  12. --     /  /___/  /  /  /___/  /  /  /         /  /______   /  /  \  \ 
  13. --    /_________/  /_________/  /__/         /_________/  /__/    \__\
  14. --
  15. --    Functional programming environment, Version 2.20 (beta-release)
  16. --    Copyright Mark P Jones 1991.
  17. --
  18. --    Standard prelude for use of overloaded values using type classes.
  19. --    Based on the Haskell standard prelude version 1.1.
  20.  
  21. help = "press :? for a list of commands"
  22.  
  23. -- Operator precedence table: -----------------------------------------------
  24.  
  25. infixl 9 !!
  26. infixr 9 .
  27. infixr 8 ^
  28. infixl 7 *
  29. infix  7 /, `div`, `rem`, `mod`
  30. infixl 6 +, -
  31. infix  5 \\
  32. infixr 5 ++, :
  33. infix  4 ==, /=, <, <=, >=, >
  34. infix  4 `elem`, `notElem`
  35. infixr 3 &&
  36. infixr 2 ||
  37.  
  38. -- Standard combinators: ----------------------------------------------------
  39.  
  40. primitive strict "primStrict" :: (a -> b) -> a -> b
  41.  
  42. const          :: a -> b -> a
  43. const k x       = k
  44.  
  45. id             :: a -> a
  46. id    x         = x
  47.  
  48. curry          :: ((a,b) -> c) -> a -> b -> c
  49. curry f a b     =  f (a,b)
  50.  
  51. uncurry        :: (a -> b -> c) -> (a,b) -> c
  52. uncurry f (a,b) = f a b
  53.  
  54. fst            :: (a,b) -> a
  55. fst (x,_)       = x
  56.  
  57. snd            :: (a,b) -> b
  58. snd (_,y)       = y
  59.  
  60. fst3           :: (a,b,c) -> a
  61. fst3 (x,_,_)    = x
  62.  
  63.  
  64.                                       97
  65.  
  66.  
  67.  
  68.  
  69. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  70.  
  71.  
  72. snd3           :: (a,b,c) -> b
  73. snd3 (_,x,_)    = x
  74.  
  75. thd3           :: (a,b,c) -> c
  76. thd3 (_,_,x)    = x
  77.  
  78. (.)           :: (b -> c) -> (a -> b) -> (a -> c)
  79. (f . g) x       = f (g x)
  80.  
  81. flip           :: (a -> b -> c) -> b -> a -> c
  82. flip  f x y     = f y x
  83.  
  84. -- Boolean functions: -------------------------------------------------------
  85.  
  86. (&&), (||)     :: Bool -> Bool -> Bool
  87. False && x      = False
  88. True  && x      = x
  89.  
  90. False || x      = x
  91. True  || x      = True
  92.  
  93. not            :: Bool -> Bool
  94. not True        = False
  95. not False       = True
  96.  
  97. and, or        :: [Bool] -> Bool
  98. and             = foldr (&&) True
  99. or              = foldr (||) False
  100.  
  101. any, all       :: (a -> Bool) -> [a] -> Bool
  102. any p           = or  . map p
  103. all p           = and . map p
  104.  
  105. otherwise      :: Bool
  106. otherwise       = True
  107.  
  108. -- Character functions: -----------------------------------------------------
  109.  
  110. primitive ord "primCharToInt" :: Char -> Int
  111. primitive chr "primIntToChar" :: Int -> Char
  112.  
  113.  
  114. isAscii, isControl, isPrint, isSpace            :: Char -> Bool
  115. isUpper, isLower, isAlpha, isDigit, isAlphanum  :: Char -> Bool
  116.  
  117. isAscii c     =  ord c < 128
  118.  
  119. isControl c   =  c < ' '    ||  c == '\DEL'
  120.  
  121. isPrint c     =  c >= ' '   &&  c <= '~'
  122.  
  123. isSpace c     =  c == ' '   || c == '\t'  || c == '\n'  || c == '\r'  ||
  124.                                c == '\f'  || c == '\v'
  125.  
  126. isUpper c     =  c >= 'A'   &&  c <= 'Z'
  127. isLower c     =  c >= 'a'   &&  c <= 'z'
  128.  
  129.  
  130.                                       98
  131.  
  132.  
  133.  
  134.  
  135. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  136.  
  137.  
  138. isAlpha c     =  isUpper c  ||  isLower c
  139. isDigit c     =  c >= '0'   &&  c <= '9'
  140. isAlphanum c  =  isAlpha c  ||  isDigit c
  141.  
  142.  
  143. toUpper, toLower      :: Char -> Char
  144.  
  145. toUpper c | isLower c  = chr (ord c - ord 'a' + ord 'A')
  146.           | otherwise  = c
  147.  
  148. toLower c | isUpper c  = chr (ord c - ord 'A' + ord 'a')
  149.           | otherwise  = c
  150.  
  151. -- Standard type classes: ---------------------------------------------------
  152.  
  153. class Eq a where
  154.     (==), (/=) :: a -> a -> Bool
  155.     x /= y      = not (x == y)
  156.  
  157. class Eq a => Ord a where
  158.     (<), (<=), (>), (>=) :: a -> a -> Bool
  159.     max, min             :: a -> a -> a
  160.  
  161.     x <  y            = x <= y && x /= y
  162.     x >= y            = y <= x
  163.     x >  y            = y < x
  164.  
  165.     max x y | x >= y  = x
  166.             | y >= x  = y
  167.     min x y | x <= y  = x
  168.             | y <= x  = y
  169.  
  170. class Ord a => Ix a where
  171.     range   :: (a,a) -> [a]
  172.     index   :: (a,a) -> a -> Int
  173.     inRange :: (a,a) -> a -> Bool
  174.  
  175. class Ord a => Enum a where
  176.     enumFrom       :: a -> [a]              -- [n..]
  177.     enumFromThen   :: a -> a -> [a]         -- [n,m..]
  178.     enumFromTo     :: a -> a -> [a]         -- [n..m]
  179.     enumFromThenTo :: a -> a -> a -> [a]    -- [n,n'..m]
  180.  
  181.     enumFromTo n m        = takeWhile (m>=) (enumFrom n)
  182.     enumFromThenTo n n' m = takeWhile ((if n'>=n then (>=) else (<=)) m)
  183.                                       (enumFromThen n n')
  184.  
  185. class Eq a => Num a where               -- simplified numeric class
  186.     (+), (-), (*), (/) :: a -> a -> a
  187.     negate             :: a -> a
  188.     fromInteger           :: Int -> a
  189.  
  190. -- Type class instances: ----------------------------------------------------
  191.  
  192. primitive primEqInt    "primEqInt",
  193.       primLeInt    "primLeInt"   :: Int -> Int -> Bool
  194.  
  195.  
  196.                                       99
  197.  
  198.  
  199.  
  200.  
  201. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  202.  
  203.  
  204. primitive primPlusInt  "primPlusInt",
  205.       primMinusInt "primMinusInt",
  206.       primDivInt   "primDivInt",
  207.       primMulInt   "primMulInt"  :: Int -> Int -> Int
  208. primitive primNegInt   "primNegInt"  :: Int -> Int
  209.  
  210. instance Eq Int  where (==) = primEqInt
  211.  
  212. instance Ord Int where (<=) = primLeInt
  213.  
  214. instance Ix Int where
  215.     range (m,n)      = [m..n]
  216.     index (m,n) i    = i - m
  217.     inRange (m,n) i  = m <= i && i <= n
  218.  
  219. instance Enum Int where
  220.     enumFrom n       = iterate (1+) n
  221.     enumFromThen n m = iterate ((m-n)+) n
  222.  
  223. instance Num Int where
  224.     (+)           = primPlusInt
  225.     (-)           = primMinusInt
  226.     (*)           = primMulInt
  227.     (/)           = primDivInt
  228.     negate        = primNegInt
  229.     fromInteger x = x
  230.  
  231. primitive primEqFloat    "primEqFloat",
  232.           primLeFloat    "primLeFloat"    :: Float -> Float -> Bool
  233. primitive primPlusFloat  "primPlusFloat", 
  234.           primMinusFloat "primMinusFloat", 
  235.           primDivFloat   "primDivFloat",
  236.           primMulFloat   "primMulFloat"   :: Float -> Float -> Float 
  237. primitive primNegFloat   "primNegFloat"   :: Float -> Float
  238. primitive primIntToFloat "primIntToFloat" :: Int -> Float
  239.  
  240. instance Eq Float where (==) = primEqFloat
  241.  
  242. instance Ord Float where (<=) = primLeFloat
  243.  
  244. instance Enum Float where
  245.     enumFrom n       = iterate (1.0+) n
  246.     enumFromThen n m = iterate ((m-n)+) n
  247.  
  248. instance Num Float where
  249.     (+)         = primPlusFloat
  250.     (-)         = primMinusFloat
  251.     (*)         = primMulFloat
  252.     (/)         = primDivFloat 
  253.     negate      = primNegFloat
  254.     fromInteger = primIntToFloat
  255.  
  256. instance Eq Char where c == d  =  ord c == ord d
  257.  
  258. instance Ord Char where c <= d  =  ord c <= ord d
  259.  
  260.  
  261.  
  262.                                       100
  263.  
  264.  
  265.  
  266.  
  267. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  268.  
  269.  
  270. instance Ix Char where
  271.     range (c,c')      = [c..c']
  272.     index (c,c') ci   = ord ci - ord c
  273.     inRange (c,c') ci = ord c <= i && i <= ord c' where i = ord ci
  274.  
  275. instance Enum Char where
  276.     enumFrom c        = map chr [ord c ..]
  277.     enumFromThen c c' = map chr [ord c, ord c' ..]
  278.  
  279. instance Eq a => Eq [a] where
  280.     []     == []     =  True
  281.     []     == (y:ys) =  False
  282.     (x:xs) == []     =  False
  283.     (x:xs) == (y:ys) =  x==y && xs==ys
  284.  
  285. instance Ord a => Ord [a] where
  286.     []     <= _      =  True
  287.     (_:_)  <= []     =  False
  288.     (x:xs) <= (y:ys) =  x<y || (x==y && xs<=ys)
  289.  
  290. instance (Eq a, Eq b) => Eq (a,b) where
  291.     (x,y) == (u,v)  =  x==u && y==v
  292.  
  293. instance Eq Bool where
  294.     True  == True   =  True
  295.     False == False  =  True
  296.     _     == _      =  False
  297.  
  298. -- Standard numerical functions: --------------------------------------------
  299.  
  300. primitive div    "primDivInt",
  301.           rem    "primRemInt",
  302.           mod    "primModInt"    :: Int -> Int -> Int
  303.  
  304. subtract  :: Num a => a -> a -> a
  305. subtract   = flip (-)
  306.  
  307. even, odd :: Int -> Bool
  308. even x     = x `rem` 2 == 0
  309. odd        = not . even
  310.  
  311. gcd       :: Int -> Int -> Int
  312. gcd x y    = gcd' (abs x) (abs y)
  313.              where gcd' x 0 = x
  314.                    gcd' x y = gcd' y (x `rem` y)
  315.  
  316. lcm       :: Int -> Int -> Int
  317. lcm _ 0    = 0
  318. lcm 0 _    = 0
  319. lcm x y    = abs ((x `div` gcd x y) * y)
  320.  
  321. (^)       :: Int -> Int -> Int
  322. x ^ 0      = 1
  323. x ^ (n+1)  = f x n x
  324.              where f _ 0 y = y
  325.                    f x n y = g x n where
  326.  
  327.  
  328.                                       101
  329.  
  330.  
  331.  
  332.  
  333. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  334.  
  335.  
  336.                              g x n | even n    = g (x*x) (n`div`2)
  337.                                    | otherwise = f x (n-1) (x*y)
  338.  
  339. abs :: Int -> Int
  340. abs x    | x >= 0  = x
  341.          | x <  0  = - x
  342.  
  343. signum :: Int -> Int
  344. signum x | x == 0  = 0
  345.          | x > 0   = 1
  346.          | x < 0   = -1
  347.  
  348. sum, product    :: [Int] -> Int
  349. sum              = foldl' (+) 0
  350. product          = foldl' (*) 1
  351.  
  352. sums, products    :: [Int] -> [Int]
  353. sums             = scanl (+) 0
  354. products         = scanl (*) 1
  355.  
  356. -- Standard list processing functions: --------------------------------------
  357.  
  358. head             :: [a] -> a
  359. head (x:_)        = x
  360.  
  361. last             :: [a] -> a
  362. last [x]          = x
  363. last (_:xs)       = last xs
  364.  
  365. tail             :: [a] -> [a]
  366. tail (_:xs)       = xs
  367.  
  368. init             :: [a] -> [a]
  369. init [x]          = [x]
  370. init (x:xs)       = x : init xs
  371.  
  372. (++)             :: [a] -> [a] -> [a]    -- append lists.  Associative with
  373. []     ++ ys      = ys                   -- left and right identity [].
  374. (x:xs) ++ ys      = x:(xs++ys)
  375.  
  376. length         :: [a] -> Int           -- calculate length of list
  377. length            = foldl' (\n _ -> n+1) 0
  378.  
  379. (!!)             :: [a] -> Int -> a      -- xs!!n selects the nth element of
  380. (x:_)  !! 0       = x                    -- the list xs (first element xs!!0)
  381. (_:xs) !! (n+1)   = xs !! n              -- for any n < length xs.
  382.  
  383. iterate          :: (a -> a) -> a -> [a] -- generate the infinite list
  384. iterate f x       = x : iterate f (f x)  -- [x, f x, f (f x), ...
  385.  
  386. repeat           :: a -> [a]             -- generate the infinite list
  387. repeat x          = xs where xs = x:xs   -- [x, x, x, x, ...
  388.  
  389. cycle            :: [a] -> [a]           -- generate the infinite list
  390. cycle xs          = xs' where xs'=xs++xs'-- xs ++ xs ++ xs ++ ...
  391.  
  392.  
  393.  
  394.                                       102
  395.  
  396.  
  397.  
  398.  
  399. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  400.  
  401.  
  402. copy             :: Int -> a -> [a]      -- make list of n copies of x
  403. copy n x          = take n xs where xs = x:xs
  404.  
  405. nub              :: Eq a => [a] -> [a]   -- remove duplicates from list
  406. nub []            = []
  407. nub (x:xs)        = x : nub (filter (x/=) xs)
  408.  
  409. reverse          :: [a] -> [a]           -- reverse elements of list
  410. reverse           = foldl (flip (:)) []
  411.  
  412. elem, notElem    :: Eq a => a -> [a] -> Bool
  413. elem              = any . (==)           -- test for membership in list
  414. notElem           = all . (/=)           -- test for non-membership
  415.  
  416. maximum, minimum :: Ord a => [a] -> a
  417. maximum           = foldl1 max          -- max element in non-empty list
  418. minimum           = foldl1 min          -- min element in non-empty list
  419.  
  420. concat           :: [[a]] -> [a]        -- concatenate list of lists
  421. concat            = foldr (++) []
  422.  
  423. transpose        :: [[a]] -> [[a]]      -- transpose list of lists
  424. transpose         = foldr
  425.                       (\xs xss -> zipWith (:) xs (xss ++ repeat []))
  426.                       []
  427.  
  428. -- null provides a simple and efficient way of determining whether a given
  429. -- list is empty, without using (==) and hence avoiding a constraint of the
  430. -- form Eq [a].
  431.  
  432. null             :: [a] -> Bool
  433. null []           = True
  434. null (_:_)        = False
  435.  
  436. -- (\\) is used to remove the first occurrence of each element in the second
  437. -- list from the first list.  It is a kind of inverse of (++) in the sense
  438. -- that  (xs ++ ys) \\ xs = ys for any finite list xs of proper values xs.
  439.  
  440. (\\)             :: Eq a => [a] -> [a] -> [a]
  441. (\\)              = foldl del
  442.                     where []     `del` _  = []
  443.                           (x:xs) `del` y
  444.                              | x == y     = xs
  445.                              | otherwise  = x : xs `del` y
  446.  
  447.  
  448. -- map f xs applies the function f to each element of the list xs returning
  449. -- the corresponding list of results.  filter p xs returns the sublist of xs
  450. -- containing those elements which satisfy the predicate p.
  451.  
  452. map              :: (a -> b) -> [a] -> [b]
  453. map f []          = []
  454. map f (x:xs)      = f x : map f xs
  455.  
  456. filter           :: (a -> Bool) -> [a] -> [a]
  457. filter _ []       = []
  458.  
  459.  
  460.                                       103
  461.  
  462.  
  463.  
  464.  
  465. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  466.  
  467.  
  468. filter p (x:xs)
  469.     | p x         = x : xs'
  470.     | otherwise   = xs'
  471.                   where xs' = filter p xs
  472.  
  473. -- Fold primitives:  The foldl and scanl functions, variants foldl1 and
  474. -- scanl1 for non-empty lists, and strict variants foldl' scanl' describe
  475. -- common patterns of recursion over lists.  Informally:
  476. --
  477. --  foldl f a [x1, x2, ..., xn]  = f (...(f (f a x1) x2)...) xn
  478. --                               = (...((a `f` x1) `f` x2)...) `f` xn
  479. -- etc...
  480. --
  481. -- The functions foldr, scanr and variants foldr1, scanr1 are duals of these
  482. -- functions:
  483. -- e.g.  foldr f a xs = foldl (flip f) a (reverse xs)  for finite lists xs.
  484.  
  485. foldl            :: (a -> b -> a) -> a -> [b] -> a
  486. foldl f z []      = z
  487. foldl f z (x:xs)  = foldl f (f z x) xs
  488.  
  489. foldl1           :: (a -> a -> a) -> [a] -> a
  490. foldl1 f (x:xs)   = foldl f x xs
  491.  
  492. foldl'           :: (a -> b -> a) -> a -> [b] -> a
  493. foldl' f a []     =  a
  494. foldl' f a (x:xs) =  strict (foldl' f) (f a x) xs
  495.  
  496. scanl            :: (a -> b -> a) -> a -> [b] -> [a]
  497. scanl f q xs      = q : (case xs of
  498.                          []   -> []
  499.                          x:xs -> scanl f (f q x) xs)
  500.  
  501. scanl1           :: (a -> a -> a) -> [a] -> [a]
  502. scanl1 f (x:xs)   = scanl f x xs
  503.  
  504. scanl'           :: (a -> b -> a) -> a -> [b] -> [a]
  505. scanl' f q xs     = q : (case xs of
  506.                          []   -> []
  507.                          x:xs -> strict (scanl' f) (f q x) xs)
  508.  
  509. foldr            :: (a -> b -> b) -> b -> [a] -> b
  510. foldr f z []      = z
  511. foldr f z (x:xs)  = f x (foldr f z xs)
  512.  
  513. foldr1           :: (a -> a -> a) -> [a] -> a
  514. foldr1 f [x]      = x
  515. foldr1 f (x:xs)   = f x (foldr1 f xs)
  516.  
  517. scanr            :: (a -> b -> b) -> b -> [a] -> [b]
  518. scanr f q0 []     = [q0]
  519. scanr f q0 (x:xs) = f x q : qs
  520.                     where qs@(q:_) = scanr f q0 xs
  521.  
  522. scanr1           :: (a -> a -> a) -> [a] -> [a]
  523. scanr1 f [x]      = [x]
  524.  
  525.  
  526.                                       104
  527.  
  528.  
  529.  
  530.  
  531. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  532.  
  533.  
  534. scanr1 f (x:xs)   = f x q : qs
  535.                     where qs@(q:_) = scanr1 f xs
  536.  
  537. -- List breaking functions:
  538. --
  539. --   take n xs       returns the first n elements of xs
  540. --   drop n xs       returns the remaining elements of xs
  541. --   splitAt n xs    = (take n xs, drop n xs)
  542. --
  543. --   takeWhile p xs  returns the longest initial segment of xs whose
  544. --                   elements satisfy p
  545. --   dropWhile p xs  returns the remaining portion of the list
  546. --   span p xs       = (takeWhile p xs, dropWhile p xs)
  547. --
  548. --   takeUntil p xs  returns the list of elements upto and including the
  549. --                   first element of xs which satisfies p
  550.  
  551. take                :: Int -> [a] -> [a]
  552. take 0     _         = []
  553. take _     []        = []
  554. take (n+1) (x:xs)    = x : take n xs
  555.  
  556. drop                :: Int -> [a] -> [a]
  557. drop 0     xs        = xs
  558. drop _     []        = []
  559. drop (n+1) (_:xs)    = drop n xs
  560.  
  561. splitAt             :: Int -> [a] -> ([a], [a])
  562. splitAt 0     xs     = ([],xs)
  563. splitAt _     []     = ([],[])
  564. splitAt (n+1) (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt n xs
  565.  
  566. takeWhile           :: (a -> Bool) -> [a] -> [a]
  567. takeWhile p []       = []
  568. takeWhile p (x:xs)
  569.          | p x       = x : takeWhile p xs
  570.          | otherwise = []
  571.  
  572. takeUntil           :: (a -> Bool) -> [a] -> [a]
  573. takeUntil p []       = []
  574. takeUntil p (x:xs)
  575.        | p x         = [x]
  576.        | otherwise   = x : takeUntil p xs
  577.  
  578. dropWhile           :: (a -> Bool) -> [a] -> [a]
  579. dropWhile p []       = []
  580. dropWhile p xs@(x:xs')
  581.          | p x       = dropWhile p xs'
  582.          | otherwise = xs
  583.  
  584. span, break         :: (a -> Bool) -> [a] -> ([a],[a])
  585. span p []            = ([],[])
  586. span p xs@(x:xs')
  587.          | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  588.          | otherwise = ([],xs)
  589. break p              = span (not . p)
  590.  
  591.  
  592.                                       105
  593.  
  594.  
  595.  
  596.  
  597. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  598.  
  599.  
  600. -- Text processing:
  601. --   lines s     returns the list of lines in the string s.
  602. --   words s     returns the list of words in the string s.
  603. --   unlines ls  joins the list of lines ls into a single string
  604. --               with lines separated by newline characters.
  605. --   unwords ws  joins the list of words ws into a single string
  606. --               with words separated by spaces.
  607.  
  608. lines     :: String -> [String]
  609. lines ""   = []
  610. lines s    = l : (if null s' then [] else lines (tail s'))
  611.              where (l, s') = break ('\n'==) s
  612.  
  613. words     :: String -> [String]
  614. words s    = case dropWhile isSpace s of
  615.                   "" -> []
  616.                   s' -> w : words s''
  617.                         where (w,s'') = break isSpace s'
  618.  
  619. unlines   :: [String] -> String
  620. unlines    = concat . map (\l -> l ++ "\n")
  621.  
  622. unwords   :: [String] -> String
  623. unwords [] = []
  624. unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
  625.  
  626. -- Merging and sorting lists:
  627.  
  628. merge               :: Ord a => [a] -> [a] -> [a] 
  629. merge []     ys      = ys
  630. merge xs     []      = xs
  631. merge (x:xs) (y:ys)
  632.         | x <= y     = x : merge xs (y:ys)
  633.         | otherwise  = y : merge (x:xs) ys
  634.  
  635. sort                :: Ord a => [a] -> [a]
  636. sort                 = foldr insert []
  637.  
  638. insert              :: Ord a => a -> [a] -> [a]
  639. insert x []          = [x]
  640. insert x (y:ys)
  641.         | x <= y     = x:y:ys
  642.         | otherwise  = y:insert x ys
  643.  
  644. qsort               :: Ord a => [a] -> [a]
  645. qsort []             = []
  646. qsort (x:xs)         = qsort [ u | u<-xs, u<x ] ++
  647.                              [ x ] ++
  648.                        qsort [ u | u<-xs, u>=x ]
  649.  
  650. -- zip and zipWith families of functions:
  651.  
  652. zip  :: [a] -> [b] -> [(a,b)]
  653. zip   = zipWith  (\a b -> (a,b))
  654.  
  655. zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
  656.  
  657.  
  658.                                       106
  659.  
  660.  
  661.  
  662.  
  663. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  664.  
  665.  
  666. zip3  = zipWith3 (\a b c -> (a,b,c))
  667.  
  668. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
  669. zip4  = zipWith4 (\a b c d -> (a,b,c,d))
  670.  
  671. zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
  672. zip5  = zipWith5 (\a b c d e -> (a,b,c,d,e))
  673.  
  674. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a,b,c,d,e,f)]
  675. zip6  = zipWith6 (\a b c d e f -> (a,b,c,d,e,f))
  676.  
  677. zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a,b,c,d,e,f,g)]
  678. zip7  = zipWith7 (\a b c d e f g -> (a,b,c,d,e,f,g))
  679.  
  680.  
  681. zipWith                  :: (a->b->c) -> [a]->[b]->[c]
  682. zipWith z (a:as) (b:bs)   = z a b : zipWith z as bs
  683. zipWith _ _      _        = []
  684.  
  685. zipWith3                 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
  686. zipWith3 z (a:as) (b:bs) (c:cs)
  687.                           = z a b c : zipWith3 z as bs cs
  688. zipWith3 _ _ _ _          = []
  689.  
  690. zipWith4                 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
  691. zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
  692.                           = z a b c d : zipWith4 z as bs cs ds
  693. zipWith4 _ _ _ _ _        = []
  694.  
  695. zipWith5                 :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f]
  696. zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
  697.                           = z a b c d e : zipWith5 z as bs cs ds es
  698. zipWith5 _ _ _ _ _ _      = []
  699.  
  700. zipWith6                 :: (a->b->c->d->e->f->g)
  701.                             -> [a]->[b]->[c]->[d]->[e]->[f]->[g]
  702. zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
  703.                           = z a b c d e f : zipWith6 z as bs cs ds es fs
  704. zipWith6 _ _ _ _ _ _ _    = []
  705.  
  706. zipWith7                 :: (a->b->c->d->e->f->g->h)
  707.                              -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
  708. zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
  709.                           = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
  710. zipWith7 _ _ _ _ _ _ _ _  = []
  711.  
  712. -- Formatted output: --------------------------------------------------------
  713.  
  714. primitive primPrint "primPrint"  :: Int -> a -> String -> String
  715.  
  716. show'       :: a -> String
  717. show' x      = primPrint 0 x []
  718.  
  719. cjustify, ljustify, rjustify :: Int -> String -> String
  720.  
  721. cjustify n s = space halfm ++ s ++ space (m - halfm)
  722.  
  723.  
  724.                                       107
  725.  
  726.  
  727.  
  728.  
  729. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  730.  
  731.  
  732.                where m     = n - length s
  733.                      halfm = m `div` 2
  734. ljustify n s = s ++ space (n - length s)
  735. rjustify n s = space (n - length s) ++ s
  736.  
  737. space       :: Int -> String
  738. space n      = copy n ' '
  739.  
  740. layn        :: [String] -> String
  741. layn         = lay 1 where lay _ []     = []
  742.                            lay n (x:xs) = rjustify 4 (show n) ++ ") "
  743.                                            ++ x ++ "\n" ++ lay (n+1) xs
  744.  
  745. -- Miscellaneous: -----------------------------------------------------------
  746.  
  747. until                  :: (a -> Bool) -> (a -> a) -> a -> a
  748. until p f x | p x       = x
  749.             | otherwise = until p f (f x)
  750.  
  751. until'                 :: (a -> Bool) -> (a -> a) -> a -> [a]
  752. until' p f              = takeUntil p . iterate f
  753.  
  754. error                  :: String -> a
  755. error msg | False       = error msg
  756.  
  757. undefined              :: a
  758. undefined | False       = undefined
  759.  
  760. asTypeOf               :: a -> a -> a
  761. x `asTypeOf` _          = x
  762.  
  763. -- A trimmed down version of the Haskell Text class: ------------------------
  764.  
  765. type  ShowS   = String -> String
  766.  
  767. class Text a where 
  768.     showsPrec      :: Int -> a -> ShowS
  769.     showList       :: [a] -> ShowS
  770.  
  771.     showsPrec       = primPrint
  772.     showList []     = showString "[]"
  773.     showList (x:xs) = showChar '[' . shows x . showl xs
  774.                       where showl []     = showChar ']'
  775.                             showl (x:xs) = showChar ',' . shows x . showl xs
  776.  
  777. shows      :: Text a => a -> ShowS
  778. shows       =  showsPrec 0
  779.  
  780. show       :: Text a => a -> String
  781. show x      =  shows x ""
  782.  
  783. showChar   :: Char -> ShowS
  784. showChar    =  (:)
  785.  
  786. showString :: String -> ShowS
  787. showString  =  (++)
  788.  
  789.  
  790.                                       108
  791.  
  792.  
  793.  
  794.  
  795. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  796.  
  797.  
  798. instance Text ()
  799.  
  800. instance Text Int
  801.  
  802. instance Text Char where
  803.     showList cs = showChar '"' . showl cs
  804.                   where showl ""       = showChar '"'
  805.                         showl ('"':cs) = showString "\\\"" . showl cs
  806.                         showl (c:cs)   = showChar c . showl cs
  807.             -- Haskell has   showLitChar c . showl cs
  808.  
  809. instance Text a => Text [a]  where
  810.     showsPrec p = showList
  811.  
  812. instance (Text a, Text b) => Text (a,b) where
  813.     showsPrec p (x,y) = showChar '(' . shows x . showChar ',' .
  814.                                        shows y . showChar ')'
  815.  
  816. -- I/O functions and definitions: -------------------------------------------
  817.  
  818. stdin         =  "stdin"
  819. stdout        =  "stdout"
  820. stderr        =  "stderr"
  821. stdecho       =  "stdecho"
  822.  
  823. data Request  =  -- file system requests:
  824.                 ReadFile      String         
  825.               | WriteFile     String String
  826.               | AppendFile    String String
  827.                  -- channel system requests:
  828.               | ReadChan      String 
  829.               | AppendChan    String String
  830.                  -- environment requests:
  831.               | Echo          Bool
  832.  
  833. data Response = Success
  834.               | Str String 
  835.               | Failure IOError
  836.  
  837. data IOError  = WriteError   String
  838.               | ReadError    String
  839.               | SearchError  String
  840.               | FormatError  String
  841.               | OtherError   String
  842.  
  843. type Dialogue  =  [Response] -> [Request]
  844. type SuccCont  =                Dialogue
  845. type StrCont   =  String     -> Dialogue
  846. type FailCont  =  IOError    -> Dialogue
  847.  
  848. done          ::                                                Dialogue
  849. readFile      :: String ->           FailCont -> StrCont     -> Dialogue
  850. writeFile     :: String -> String -> FailCont -> SuccCont    -> Dialogue
  851. appendFile    :: String -> String -> FailCont -> SuccCont    -> Dialogue
  852. readChan      :: String ->           FailCont -> StrCont     -> Dialogue
  853. appendChan    :: String -> String -> FailCont -> SuccCont    -> Dialogue
  854.  
  855.  
  856.                                       109
  857.  
  858.  
  859.  
  860.  
  861. Introduction to Gofer         APPENDIX B: CONTENTS OF STANDARD PRELUDE          
  862.  
  863.  
  864. echo          :: Bool ->             FailCont -> SuccCont    -> Dialogue
  865.  
  866. done resps    =  []
  867. readFile name fail succ resps =
  868.      (ReadFile name) : strDispatch fail succ resps
  869. writeFile name contents fail succ resps =
  870.     (WriteFile name contents) : succDispatch fail succ resps
  871. appendFile name contents fail succ resps =
  872.     (AppendFile name contents) : succDispatch fail succ resps
  873. readChan name fail succ resps =
  874.     (ReadChan name) : strDispatch fail succ resps
  875. appendChan name contents fail succ resps =
  876.     (AppendChan name contents) : succDispatch fail succ resps
  877. echo bool fail succ resps =
  878.     (Echo bool) : succDispatch fail succ resps
  879.  
  880. strDispatch fail succ (resp:resps) = 
  881.             case resp of Str val     -> succ val resps
  882.                          Failure msg -> fail msg resps
  883.  
  884. succDispatch fail succ (resp:resps) = 
  885.             case resp of Success     -> succ resps
  886.                          Failure msg -> fail msg resps
  887.  
  888. abort           :: FailCont
  889. abort err        = done
  890.  
  891. exit            :: FailCont
  892. exit err         = appendChan stdout msg abort done
  893.                    where msg = case err of ReadError s   -> s
  894.                                            WriteError s  -> s
  895.                                            SearchError s -> s
  896.                                            FormatError s -> s
  897.                                            OtherError s  -> s
  898.  
  899. print           :: Text a => a -> Dialogue
  900. print x          = appendChan stdout (show x) abort done
  901.  
  902. prints          :: Text a => a -> String -> Dialogue
  903. prints x s       = appendChan stdout (shows x s) abort done
  904.  
  905. interact    :: (String -> String) -> Dialogue
  906. interact f     = readChan stdin abort
  907.                 (\x -> appendChan stdout (f x) abort done)
  908.  
  909. run        :: (String -> String) -> Dialogue
  910. run f         = echo False abort (interact f)
  911.  
  912. -- End of Gofer standard prelude: --------------------------------------------
  913.  
  914.  
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921.  
  922.                                       110
  923.  
  924.  
  925.